using FBroSharp;
using FBroSharp.Const;
using FBroSharp.Event;
using FBroSharp.Lib;
using FBroSharp.VIP;
using System;
using System.Reflection;
using System.Text;

namespace BaseTest
{
    public class InitEvent : FBroInitEvent
    {
        // 存储修改规则的变量
        public string changerWssText = "";
        public byte[] changeWssData = null;
        public IFBroSharpDOMWssClient wss = null;

        // ⚠️⚠️⚠️ CRITICAL: Method signature must be EXACTLY as below!
        // ✅ CORRECT: OnBeforeCommandLineProcessing(string, IFBroSharpCommandLine) - Note the 'I' prefix!
        public override void OnBeforeCommandLineProcessing(string process_type, IFBroSharpCommandLine cmd)
        {
            cmd.DisableGpuBlockList();
            cmd.DisableGpuCache();

            Console.WriteLine(MethodBase.GetCurrentMethod().Name + ":" + process_type + cmd.IsReadOnly() + cmd.GetProgram());
        }

        //初始化完毕
        public override void OnContextInitialized()
        {
            Console.WriteLine(MethodBase.GetCurrentMethod().Name);
        }

        public override void OnBeforeChildProcessLaunch(IFBroSharpCommandLine command_line)
        {
            Console.WriteLine(MethodBase.GetCurrentMethod().Name + ":" + command_line.IsReadOnly() + command_line.GetProgram());
        }

        // ===== WebSocket 拦截功能 =====
        
        // 1. 接收主进程发送的消息（用于设置修改规则）
        public override void ReceiveMainProcessMessage(IFBroSharpBrowser browser, string name, byte[] message)
        {
            if (name == "websocketchangetext")
            {
                // 设置要修改的文本
                changerWssText = Encoding.Default.GetString(message);
                Console.WriteLine($"[InitEvent] 设置 WebSocket 文本修改规则: {changerWssText}");
            }
            else if (name == "websocketsendtext")
            {
                // 主动发送文本消息
                string textToSend = Encoding.Default.GetString(message);
                wss?.Send(textToSend);
                Console.WriteLine($"[InitEvent] 主动发送 WebSocket 文本消息: {textToSend}");
            }
            else if (name == "websocketchangedata")
            {
                // 设置要修改的二进制数据
                changeWssData = new byte[message.Length];
                message.CopyTo(changeWssData, 0);
                Console.WriteLine($"[InitEvent] 设置 WebSocket 二进制修改规则，长度: {message.Length}");
            }
            else if (name == "websocketsenddata")
            {
                // 主动发送二进制消息
                wss?.SendData(message);
                Console.WriteLine($"[InitEvent] 主动发送 WebSocket 二进制消息，长度: {message.Length}");
            }
            else if (name == "websocketclear")
            {
                // 清除所有修改规则
                changerWssText = "";
                changeWssData = null;
                Console.WriteLine("[InitEvent] 清除所有 WebSocket 修改规则");
            }
        }

        // 2. WebSocket 连接时触发
        public override void VIP_OnWebSocketClientConnect(IFBroSharpBrowser browser, IFBroSharpFrame frame, 
            IFBroSharpDOMWssClient websocket, ref string returl, ref string protocols)
        {
            wss = new FBroSharpDOMWssClient(websocket);

            Console.WriteLine($"[InitEvent] WebSocket 连接: {websocket.GetAddress()}");

            // 将连接信息反馈给主进程
            var processMessageCon = browser.GetOwnProcessMessageControl();
            if (processMessageCon != null && processMessageCon.IsValid)
            {
                string sendData = $"WebSocket连接||{websocket.GetAddress()}||{returl}||{protocols}";
                processMessageCon.ClientSendByBrowser("websocket", Encoding.Default.GetBytes(sendData));
            }
        }

        // 3. WebSocket 关闭时触发
        public override void VIP_OnWebSocketClientClose(IFBroSharpBrowser browser, IFBroSharpFrame frame, 
            IFBroSharpDOMWssClient websocket)
        {
            Console.WriteLine($"[InitEvent] WebSocket 关闭: {websocket.GetAddress()}");
            
            // 将关闭信息反馈给主进程
            var processMessageCon = browser.GetOwnProcessMessageControl();
            if (processMessageCon != null && processMessageCon.IsValid)
            {
                string sendData = $"WebSocket关闭||{websocket.GetAddress()}";
                processMessageCon.ClientSendByBrowser("websocket", Encoding.Default.GetBytes(sendData));
            }
            
            wss = null;
        }

        // 4. WebSocket 发送消息时拦截（关键方法）
        public override bool VIP_OnWebSocketClientSend(IFBroSharpBrowser browser, IFBroSharpFrame frame, 
            IFBroSharpDOMWssClient websocket, int type, ref byte[] data)
        {
            // 数据类型：0=文本，1=ArrayBuffer，2=Blob
            string dataPreview = "";
            
            if (type == 0) // 文本类型
            {
                dataPreview = Encoding.UTF8.GetString(data);
                
                // 如果设置了修改规则，则修改数据
                if (!string.IsNullOrEmpty(changerWssText))
                {
                    // ⚠️ 注意：修改的数据必须是UTF8类型
                    data = Encoding.UTF8.GetBytes(changerWssText);
                    Console.WriteLine($"[InitEvent] WebSocket 发送（已修改）: {changerWssText}");
                }
                else
                {
                    Console.WriteLine($"[InitEvent] WebSocket 发送: {dataPreview}");
                }
            }
            else // 二进制类型
            {
                dataPreview = $"[二进制数据，长度: {data.Length}]";
                
                if (changeWssData != null && changeWssData.Length > 0)
                {
                    data = changeWssData;
                    Console.WriteLine($"[InitEvent] WebSocket 发送（已修改）: {dataPreview}");
                }
                else
                {
                    Console.WriteLine($"[InitEvent] WebSocket 发送: {dataPreview}");
                }
            }
            
            // 将发送信息反馈给主进程
            var processMessageCon = browser.GetOwnProcessMessageControl();
            if (processMessageCon != null && processMessageCon.IsValid)
            {
                string sendData = $"发送||{type}||{dataPreview}||{data.Length}";
                processMessageCon.ClientSendByBrowser("websocket", Encoding.Default.GetBytes(sendData));
            }
            
            return false; // 返回false继续发送，返回true阻止发送
        }

        // 5. WebSocket 接收消息时拦截
        public override bool VIP_OnWebSocketClientMessage(IFBroSharpBrowser browser, IFBroSharpFrame frame, 
            IFBroSharpDOMWssClient websocket, int type, ref byte[] data)
        {
            // 数据类型：0=文本，1=ArrayBuffer，2=Blob
            string dataPreview = "";
            
            if (type == 0) // 文本类型
            {
                dataPreview = Encoding.UTF8.GetString(data);
                Console.WriteLine($"[InitEvent] WebSocket 接收: {dataPreview}");
            }
            else // 二进制类型
            {
                dataPreview = $"[二进制数据，长度: {data.Length}]";
                Console.WriteLine($"[InitEvent] WebSocket 接收: {dataPreview}");
            }
            
            // 将接收到的数据反馈给主进程进行显示
            var processMessageCon = browser.GetOwnProcessMessageControl();
            if (processMessageCon != null && processMessageCon.IsValid)
            {
                string sendData = $"接收||{type}||{dataPreview}||{data.Length}";
                processMessageCon.ClientSendByBrowser("websocket", Encoding.Default.GetBytes(sendData));
            }
            
            return false; // 返回false继续处理，返回true阻止接收
        }
    }
}

